package com.jilefojing.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jilefojing.beans.data.enums.ResponseEnum;
import com.jilefojing.beans.enums.ThirdPartyTypeEnum;
import com.jilefojing.beans.enums.foruser.StatusEnumForUser;
import com.jilefojing.beans.exception.UserContextException;
import com.jilefojing.beans.pojos.User;
import com.jilefojing.beans.pojos.enhanced.EnhancedUser;
import com.jilefojing.beans.vo.Pagination;
import com.jilefojing.context.beans.vo.UserContext;
import com.jilefojing.dao.IUserDao;
import com.jilefojing.service.IUserService;
import com.jilefojing.service.base.impl.BaseService;
import com.jilefojing.session.service.IUserContextService;
import com.jilefojing.util.Detect;
import com.jilefojing.util.QiniuUtil;

/**
 * 
 * @author jgshun
 * 
 */
@Service
public class UserService extends BaseService<User> implements IUserService {

	private static final String SCHEMA = "http";
	@Autowired
	private IUserDao userDao;
	@Autowired
	private IUserContextService userContextService;

	private static String DEFAULT_ICONNAME = "http://oe2fpvujn.bkt.clouddn.com/user/portrait/def.png";

	@Override
	public User getUserByAccount(String account) throws UserContextException {
		return userDao.getUserByAccount(account);
	}

	@Override
	public EnhancedUser getEnhancedUserByThirdParty(String thirdPartyId,
			ThirdPartyTypeEnum thirdPartyType, UserContext userContext)
			throws UserContextException {
		User user = userDao.getUserByThirdParty(thirdPartyId, thirdPartyType);
		if (user == null) {
			throw new UserContextException(ResponseEnum.USER_NOT_EXIST);
		}
		List<User> users = new ArrayList<User>();
		users.add(user);

		List<EnhancedUser> enhancedUsers = this
				.conventUsersToEnhancedUsers(users);

		EnhancedUser enhancedUser = enhancedUsers.get(0);

		if (enhancedUser.getStatus() == StatusEnumForUser.LOCKED) {
			throw new UserContextException(ResponseEnum.USER_LOCKED);
		} else if (enhancedUser.getStatus() != StatusEnumForUser.VALID) {
			throw new UserContextException(ResponseEnum.USER_INVALID);
		}

		return enhancedUser;
	}

	@Override
	public EnhancedUser getEnhancedUserByAccount(String account)
			throws UserContextException {
		if (!Detect.notEmpty(account) || account.trim().length() == 0) {
			throw new IllegalArgumentException("[账号不能为空]");
		}
		User user = userDao.getUserByAccount(account);
		if (user == null) {
			throw new UserContextException(ResponseEnum.USER_NOT_EXIST);
		}
		List<User> users = new ArrayList<User>();
		users.add(user);

		List<EnhancedUser> enhancedUsers = this
				.conventUsersToEnhancedUsers(users);

		EnhancedUser enhancedUser = enhancedUsers.get(0);

		if (enhancedUser.getStatus() == StatusEnumForUser.LOCKED) {
			throw new UserContextException(ResponseEnum.USER_LOCKED);
		} else if (enhancedUser.getStatus() != StatusEnumForUser.VALID) {
			throw new UserContextException(ResponseEnum.USER_INVALID);
		}

		return enhancedUser;
	}

	@Override
	public List<EnhancedUser> conventUsersToEnhancedUsers(List<User> users) {
		List<EnhancedUser> enhancedUsers = new ArrayList<EnhancedUser>();
		for (User user : users) {
			enhancedUsers.add(new EnhancedUser(user));
		}
		for (EnhancedUser _EnhancedUser : enhancedUsers) {

			if (!Detect.notEmpty(_EnhancedUser.getPortraitUrl())) {
				_EnhancedUser.setPortraitUrl(DEFAULT_ICONNAME);
			} else if (Detect.notEmpty(_EnhancedUser.getPortraitUrl())
					&& !_EnhancedUser.getPortraitUrl().toLowerCase()
							.startsWith(SCHEMA)) {
				_EnhancedUser.setPortraitUrl(QiniuUtil.getImagesDomain()
						+ _EnhancedUser.getPortraitUrl());
			}
		}
		return enhancedUsers;
	}

	@Override
	public EnhancedUser getEnhancedUser(long id) {
		List<Long> ids = new ArrayList<Long>();
		ids.add(id);
		List<EnhancedUser> enhancedUsers = this.getEnhancedUsers(ids);
		if (!Detect.notEmpty(enhancedUsers)) {
			return null;
		}
		return enhancedUsers.get(0);
	}

	@Override
	public List<EnhancedUser> getEnhancedUsers(List<Long> ids) {
		List<User> users = userDao.getByIds(ids);
		if (!Detect.notEmpty(users)) {
			return null;
		}
		List<EnhancedUser> enhancedUsers = this
				.conventUsersToEnhancedUsers(users);

		return enhancedUsers;
	}

	@Override
	public Pagination<EnhancedUser> getPagination(
			List<StatusEnumForUser> statuses,
			Pagination<EnhancedUser> pagination) {

		@SuppressWarnings("unchecked")
		Pagination<User> _userPagination = userDao.getPagination(statuses,
				pagination.copy());
		pagination.setCount(_userPagination.getCount());
		if (!Detect.notEmpty(_userPagination.getItems())) {
			return pagination;
		}

		pagination.setItems(this.conventUsersToEnhancedUsers(_userPagination
				.getItems()));
		return pagination;
	}

	@Override
	public User add(User user, UserContext userContext)
			throws UserContextException {
		String account = Detect.notEmpty(user.getTelphone()) ? user
				.getTelphone() : Detect.notEmpty(user.getEmail()) ? user
				.getEmail() : user.getName();
		if (!Detect.notEmpty(account)) {
			throw new UserContextException("[账户不能为空]");
		}

		User dbUser = userDao.getUserByAccount(account);
		if (dbUser != null) {
			throw new UserContextException(ResponseEnum.USER_EXIST);
		}

		Date date = new Date();

		User record = new User();
		boolean hasAcc = false;
		if (Detect.notEmpty(user.getTelphone())) {
			record.setTelphone(user.getTelphone());
			hasAcc = true;
		}
		if (!hasAcc && Detect.notEmpty(user.getEmail())) {
			record.setEmail(user.getEmail());
			hasAcc = true;
		}
		if (!hasAcc && Detect.notEmpty(user.getEmail())) {
			record.setName(user.getName());
			hasAcc = true;
		}

		record.setPassword(user.getPassword());
		record.setNickname(user.getNickname());
		record.setStatus(StatusEnumForUser.VALID.getCode());
		record.setCreateTime(date);
		record.setUpdateTime(date);

		return userDao.saveSelective(record);
	}
}
